package com.hxh.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hxh.entity.User;
import com.hxh.entity.input.UserInput;
import com.hxh.entity.output.ApiResult;
import com.hxh.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;

    @Value("${guanyida.service.url}")
    private String serviceUrl;

    //获取用户表分页
    @RequestMapping(value = "/getUser", produces = "application/json;charset=utf-8")
    public ApiResult getUser() {
        List<User> userList = userService.select(new UserInput());
        if (CollectionUtil.isNotEmpty(userList)) {
            return ApiResult.ok("获取用户成功", userList.get(0));
        } else {
            return ApiResult.ok("暂无用户");
        }
    }

    //修改用户表
    @PostMapping(value = "update")
    public ApiResult update(UserInput user) {
        boolean flag = userService.update(user);
        if (flag) {
            return ApiResult.ok("更新成功");
        } else {
            return ApiResult.fail("更新失败");
        }
    }


    @PostMapping(value = "getInfoByKey")
    public ApiResult getInfoByKey(@RequestParam String key) {
        String post = HttpUtil.post(serviceUrl + "/api/keyApi/getUserInfo", "key=" + key);
        ApiResult bean = JSONUtil.toBean(post, ApiResult.class);
        if (bean.isStatus()) {
            JSONObject data = (JSONObject) bean.getData();
            UserInput userInput = new UserInput();
            userInput.setUsername(data.getStr("username"));
            userInput.setNickName(data.getStr("nickname"));
            userInput.setEmail(data.getStr("email"));
            userInput.setCreateTime(data.getDate("createTime"));
            userInput.setKey(key);
            userService.updateByKey(userInput);
        }
        return bean;
    }


}
